import {
  Card,
  Form,
  Input,
  Button,
  Row,
  Col,
  Select,
  Table,
  message,
} from "antd";
import React, { useEffect, useState } from "react";
import {
  getHospitalListRequest,
  getProvinceRequest,
  getCityOrDistrictRequest,
  getHospitalStatusRequest,
} from "@/api/hospital/hospitalList";
import {
  getHospitalListItemType,
  getHospitalSearchParamsType,
  getHospitalListContentType,
  getProvinceType,
} from "@/api/hospital/model/hospitalListType";
import { useNavigate } from "react-router-dom";

export default function HospitalList() {
  const [form] = Form.useForm();
  // 定义内容加载是否完成
  const [isLoading, setIsLoading] = useState(false);
  //定义当前页
  const [page, setPage] = useState(1);
  //定义每页显示的数量
  const [limit, setLimit] = useState(4);
  //定义医院总数量
  const [total, setTotal] = useState(0);
  //定义请求的hoscode, hosname, hostype, provinceCode, cityCode, districtCode, status参数
  const [searchParams, setSearchParams] = useState<getHospitalSearchParamsType>(
    {}
  );
  //定义请求到的数据
  const [returnHospital, setReturnHospital] =
    useState<getHospitalListContentType>([]);
  //定义医院类型
  const [hospitalType, setHospitalType] = useState<getProvinceType>([]);
  //定义省份
  const [province, setProvince] = useState<getProvinceType>([]);
  //定义市
  const [city, setCity] = useState<getProvinceType>([]);
  //定义区
  const [district, setDistrict] = useState<getProvinceType>([]);

  const navigate = useNavigate();

  const [reRender, setReRender] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    const getHospitalList = async () => {
      const result = await getHospitalListRequest(page, limit, searchParams);
      // console.log(result.content);
      setReturnHospital(result.content);

      setTotal(result.totalElements);
      setIsLoading(false);
    };
    getHospitalList();
  }, [searchParams, page, limit, reRender]);

  useEffect(() => {
    const getProvinceList = async () => {
      const result = await getProvinceRequest();
      // console.log(result);
      setProvince(result);
    };
    getProvinceList();
  }, []);

  useEffect(() => {
    const getHospitalType = async () => {
      const result = await getCityOrDistrictRequest("10000");
      // console.log(result);
      setHospitalType(result);
    };
    getHospitalType();
  }, []);

  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      render(_: any, data: getHospitalListItemType) {
        return (
          <img
            width={100}
            src={`data:img/jpeg;base64,${data.logoData}`}
            alt=""
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: getHospitalListItemType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(_: any, data: getHospitalListItemType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: getHospitalListItemType) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      render(_: any, data: getHospitalListItemType) {
        return (
          <div>
            <Button type="primary" onClick={viewsHospitalHandle(data.id)}>
              查看
            </Button>
            <Button type="primary" onClick={gotoHospitalScheduleHandle(data.hoscode)}>
              排班
            </Button>
            <Button
              type="primary"
              onClick={changStatusHandle(data.id, data.status === 0 ? 1 : 0)}
            >
              {data.status === 0 ? "离线" : "上线"}
            </Button>
          </div>
        );
      },
    },
  ];

  const pageChangeHandle = (page: number, limit: number) => {
    // console.log(page, pageSize);
    setPage(page);
    setLimit(limit);
  };
  const getCityHandle = async (key: string) => {
    // console.log(a, b);
    // 第一个参数：key,第二个参数value
    // console.log(key);
    const result = await getCityOrDistrictRequest(key);
    // console.log(result);
    setCity(result);
    form.setFieldsValue({ cityCode: "", districtCode: "" });
    setDistrict([]);
  };
  const getStrictHandle = async (key: string) => {
    // console.log(a, b);
    // 第一个参数：key,第二个参数value
    // console.log(key);
    const result = await getCityOrDistrictRequest(key);
    // console.log(result);
    setDistrict(result);
    form.setFieldsValue({ district: "" });
  };
  //点击查询事件
  const getSelectHosResultHandle = (value: getHospitalSearchParamsType) => {
    setSearchParams(value);
  };
  // 点击清空事件
  const clearDataHandle = () => {
    setSearchParams({});
  };
  //查看医院
  const viewsHospitalHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitaldetail/${id}`);
    };
  };

  //改变上下线状态
  const changStatusHandle = (id: string, status: 0 | 1) => {
    return async () => {
      await getHospitalStatusRequest(id, status);
      message.success("改变状态成功!");
      setReRender(!reRender);
    };
  };

  //跳转到排班页面
  const gotoHospitalScheduleHandle = (hoscode:string) => {
    return ()=>{
      navigate(`/syt/hospital/Hospitalschedule/${hoscode}`);
    }
  };

  return (
    <div>
      <Card>
        <Form form={form} onFinish={getSelectHosResultHandle}>
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="provinceCode ">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={getCityHandle}
                >
                  {province.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={getStrictHandle}
                >
                  {city.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区" allowClear>
                  {district.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {hospitalType.map((item) => (
                    <Select.Option value={item.value} key={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  type="default"
                  htmlType="reset"
                  onClick={clearDataHandle}
                  style={{ marginLeft: "20px" }}
                >
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={returnHospital}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total: total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [4, 8, 12],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange: pageChangeHandle,
            showQuickJumper: true,
          }}
        />
      </Card>
    </div>
  );
}
